/**
 * description:项目工程化公共方法
 * author:
 * date:2020/04/01
 * */
const path = require("path");
const config = require("./config");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const autoprefixer = require('autoprefixer');
const flexbugs = require("postcss-flexbugs-fixes");

exports.generatorLoaders = function(loaderPre, options = {}) {
    if (typeof loaderPre !== 'string') {
        options = loaderPre;
        loaderPre = "";
    }
    let extractLoader = {loader: MiniCssExtractPlugin.loader};
    let cssLoader = {loader: "css-loader", options: {
        sourceMap: options.sourceMap
    }};
    let postcssLoader = {
        loader: 'postcss-loader',
        options: {
            plugins: [
                flexbugs,
                autoprefixer({
                    overrideBrowserslist: ["last 6 versions", "android >= 4.0", "ios >= 5.0", ">1%", "Firefox ESR", "not ie < 9"]
                })
            ]
        }
    };
    let loaders = [cssLoader, postcssLoader];
    if (loaderPre) {
        let otherLoader = {
            loader: `${loaderPre}-loader`,
            options: {
                sourceMap: options.sourceMap
            }
        };
        loaders.push(otherLoader);
    }
    if (options.extract) {
        return ["vue-style-loader", extractLoader].concat(loaders);
    } else {
        return ["vue-style-loader"].concat(loaders);
    }
};

module.exports = {
    /* dir为相对于根路径找到文件的path */
    resolve(dir) {
        // __dirname为utils文件所在路径
        return path.resolve(__dirname, '../', dir);
    },
    // 输出静态资源路径，相对于output path
    assetsPath(assetsPath) {
        return path.posix.join(config.assetsOutputDir, assetsPath);
    },
    generatorStyleLoaders(options) {
        return [
            {
                test: /\.css$/,
                use: exports.generatorLoaders(options)
            },
            {
                test: /\.less$/,
                use: exports.generatorLoaders("less", options).concat({
                    loader: 'sass-resources-loader',
                    options: {
                        resources: path.resolve(__dirname, '../client/assets/less/variable.less')//这里按照你的文件路径填写
                    }
                })
            }
        ];
    }
};
